package com.wys.aip.service;

import com.baidu.aip.face.AipFace;
import com.baidu.aip.face.MatchRequest;

import com.wys.aip.entry.TbResult;
import org.apache.commons.codec.binary.Base64;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.*;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author 韦云师
 * @date 2020/8/22 13:58
 */
@Service
public class FaceContrastService {
    private Logger logger = LoggerFactory.getLogger(FaceContrastService.class);
    //设置APPID/AK/SK
    private final String APP_ID = "17068279";
    private final String API_KEY = "XKk6nVIbX7NKI7pXSEfRbVbt";
    private final String SECRET_KEY = "MYXjAt44MWrNIPgqBWKG8gyFcgnsn41n";
    private List<TbResult> list = new ArrayList<>();
    private AipFace client = new AipFace(APP_ID, API_KEY, SECRET_KEY);

    public String getContrastResult(String type, String parameter1, String parameter2) {
        try {
            // 可选：设置网络连接参数
            client.setConnectionTimeoutInMillis(2000);
            client.setSocketTimeoutInMillis(60000);
            ArrayList<MatchRequest> requests = new ArrayList<MatchRequest>();
            //判断入参的形式,直接URL形式
            if (type.equals("URL")) {
                MatchRequest req1 = new MatchRequest(parameter1, "URL");
                MatchRequest req2 = new MatchRequest(parameter2, "URL");
                requests.add(req1);
                requests.add(req2);
            } else if (type.equals("LOCAL")) {
                File file1 = new File(parameter1);
                File file2 = new File(parameter2);
                // 读本地图片
                byte[] bytes = fileToBytes(file1);
                byte[] bytes2 = fileToBytes(file2);
                // 将字节转base64
                MatchRequest req1 = new MatchRequest(Base64.encodeBase64String(bytes), "BASE64");
                MatchRequest req2 = new MatchRequest(Base64.encodeBase64String(bytes2), "BASE64");
                requests.add(req1);
                requests.add(req2);
            } else {
                return "参数类型有误！";
            }
            // 人脸对比
            JSONObject res = client.match(requests);
            logger.info(res.toString());
            Map<String, Object> map = res.toMap();
            Map<String, Object> maps = (Map<String, Object>) map.get("result");
            BigDecimal mData = new BigDecimal(maps.get("score").toString());
            BigDecimal result = mData.setScale(2, BigDecimal.ROUND_HALF_UP);
            return "相似度为：" + result + "%";
        } catch (Exception e) {
            e.printStackTrace();
            return "对比失败！";
        }
    }

    public String batchComparison(String path) {
        File file = new File(path);
        if (file.isFile()) {
            return "该路径非文件目录";
        }
        //获取该目录下所有的文件夹名称
        File[] files = file.listFiles();
        int len = files.length;
        int count = 0;
        for (int i = 0; i < len; i++) {
            if (!files[i].isDirectory()) {
                count++;
                logger.error("路径:{}/{},不存在！", path, files[i].getName());
            } else {
                File[] targe = files[i].listFiles();
                if (targe.length != 2) {
                    logger.error("路径:{}/{},文件个数异常！", path, files[i].getName());
                    count++;
                } else {
                    list.add(doComparison(path, targe));
                }
            }
        }
        //打印结果，模拟写入库
        int size = list.size();
        for (int i = 0; i < size; i++) {
            System.out.println(list.get(i));
        }
        return "对比完毕！失败条数为：" + count;
    }

    private TbResult doComparison(String path, File[] files) {
        ArrayList<MatchRequest> requests = new ArrayList<MatchRequest>();
        TbResult tbResult = new TbResult();
        tbResult.setPath1(files[0].getPath());
        tbResult.setPath2(files[1].getPath());
        byte[] bytes1 = fileToBytes(files[0]);
        byte[] bytes2 = fileToBytes(files[1]);
        MatchRequest req1 = new MatchRequest(Base64.encodeBase64String(bytes1), "BASE64");
        MatchRequest req2 = new MatchRequest(Base64.encodeBase64String(bytes2), "BASE64");
        requests.add(req1);
        requests.add(req2);
        // 人脸对比
        JSONObject res = client.match(requests);
        Map<String, Object> map = res.toMap();
        Map<String, Object> maps = (Map<String, Object>) map.get("result");
        BigDecimal mData = new BigDecimal(maps.get("score").toString());
        tbResult.setScore(mData.doubleValue());
        return tbResult;
    }

    private byte[] fileToBytes(File file) {
        byte[] buff = null;
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
            byte[] bytes = new byte[1024];
            int n;
            while ((n = bis.read(bytes)) != -1) {
                bos.write(bytes, 0, n);
            }
            bis.close();
            buff = bos.toByteArray();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buff;
    }
}